# -*- coding: utf-8 -*-
import json
import traceback
import urllib
import vkontakte
import hashlib
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import login as django_login, authenticate
from django.contrib.auth import logout as django_logout
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from apps.users.forms.login import LoginForm
from apps.users.forms.register import RegisterForm
from apps.users.models import UserProfile
from core.decorators import render
from core.enum import REQUEST_POST
from services.vk import VKService

@csrf_exempt
def login_vkontakte(request):
    try:
        vk = VKService()

        response = json.loads(urllib.urlopen(
            "https://oauth.vk.com/access_token?client_id=2953243&client_secret=jPIMR4qRt5ps5qoEOZvg&code=%s" % request.GET.get("code")
        ).read())

        user_id = response.get("user_id", None)
        access_token = response.get("access_token", "")

        user = vk.get_user(VKService.TYPE_VK, user_id, access_token)
        auth_user = authenticate(
            username = user.email,
            password = vk.get_auth_key(VKService.TYPE_VK, user_id)
        )
        django_login(request, auth_user)
        messages.success(request, "Вы успешно прошли авторизацию")

    except Exception, e:
        traceback.print_exc()
        messages.error(request, "Ошибка авторизации. Попробуйте позже.")

    return HttpResponseRedirect("/")


@csrf_exempt
@render('users/login.html')
def login(request):

    if request.method == REQUEST_POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            django_login(request, form.user)
            messages.success(request, "Вы успешно прошли авторизацию")
            return HttpResponseRedirect("/")

    else:
        form = LoginForm(initial={
            'username': '',
            'password': ''
        })

    return {
        'form': form
    }

def logout(request):
    django_logout(request)
    messages.success(request, "Спасибо за Ваш визит. Возвращайтесь!")
    return HttpResponseRedirect("/")

@csrf_exempt
@render('users/register.html')
def register(request):

    if request.method == REQUEST_POST:
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = User.objects.create(
                username = form.cleaned_data.get("username"),
                email = form.cleaned_data.get("email")
            )
            user.set_password(form.cleaned_data.get("password"))
            user.save()
            UserProfile.objects.create(
                user = user
            )
            messages.success(request, "Поздравляем с успешной регистрацией! Теперь Вы можете авторизоваться используюя свой логин и пароль.")
            return HttpResponseRedirect("/")

    else:
        form = RegisterForm(initial={
            'username': '',
            'email': '',
            'password': '',
            'repeat_password': ''
        })

    return {
        'form': form
    }